package servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;

import pojo.User;
import tools.Tool;
import utils.db.impl.EditAccount;

/**
 * Servlet implementation class EditAccount
 */
@WebServlet("/EditAccountServlet")
public class EditAccountServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		User user=(User)session.getAttribute("user");
		String name = request.getParameter("name");
		String surname = request.getParameter("surname");
		String email = request.getParameter("email");
		int phone = Integer.parseInt(request.getParameter("phone"));
		String password = DigestUtils.md5Hex(request.getParameter("password"));
		int id = user.getId();
		
		if(name!="" && surname!="" && email!="" && phone!=0 && password!=""){
			if(Tool.checkEmailFormat(email)){
				if(Tool.checkPhoneNumber(phone)){
					if(user.getPassword().equals(password)){
						EditAccount edit = new EditAccount();
						edit.editAccount(id, name, surname, email, phone);
						user.setFirstName(name);
    					user.setLastName(surname);
    					user.setPhoneNumber(phone);
    					user.setEmail(email);
    					session.setAttribute("user", user);
    					session.setAttribute("editAccount", "Zmiany zostały wprowadzone do bazy!");
    					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    					response.setHeader("Location", "index.jsp?page=userPanel#page");
					}else{
						session.setAttribute("editAccount", "Bledne hasło do konta!");
    					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
    					response.setHeader("Location", "index.jsp?page=userPanel#page");
					}
				}else{
					//bledny telefon
					session.setAttribute("editAccount", "Błędny numer telefonu!");
					response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
					response.setHeader("Location", "index.jsp?page=userPanel#page");
				}
			}else{
				//bledny format email
				session.setAttribute("editAccount", "Błędny format email!");
				response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
				response.setHeader("Location", "index.jsp?page=userPanel#page");
			}
		}else{
			//puste pola
			session.setAttribute("editAccount", "Niektóre pola pozostały puste!");
			response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
			response.setHeader("Location", "index.jsp?page=userPanel#page");
		}
	}

}
